package com.zx.tradeclient.ctrl.index5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.ctrl.index1.DetailActivity;
import com.zx.tradeclient.ctrl.index2.BuyInfoActivity;
import com.zx.tradeclient.ctrl.index2.SupplyInfoActivity;
import com.zx.tradeclient.ctrl.index3.CompanyInfoActivity;
import com.zx.tradeclient.ctrl.index4.ProductInfoActivity;
import com.zx.tradeclient.entity.FavInfo;

public class FavoriteList {

	private NewsListAdapter newsListAdapter;
	private LoadMoreListViewWithProgress news_view;
	private LoadMoreListView news_listView;
	private ArrayList<FavInfo> newsList = new ArrayList<FavInfo>();
	private int page;
	private TradeApp app;
	private ImageLoader imageLoader;
	private int type;
	private Context content;

	public FavoriteList(final Context context, View view, int ftype) {
		content = context;
		page = 0;
		type = ftype;
		imageLoader = ((TradeApp) context.getApplicationContext()).imageLoader;
		init();
		initview();
		app = (TradeApp) context.getApplicationContext();
		news_view = (LoadMoreListViewWithProgress) view.findViewById(R.id.list);
		news_listView = news_view.getListView();
		newsListAdapter = new NewsListAdapter(context, newsList);
		news_listView.setAdapter(newsListAdapter);
		news_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
				Intent intent = new Intent();
				if (newsList.get(position).getType().equals("1")) {
					intent = new Intent(context, DetailActivity.class);
					intent.putExtra("newsId", newsList.get(position).getInfoId());
				} else if (newsList.get(position).getType().equals("2")) {
					intent = new Intent(context, ProductInfoActivity.class);
					intent.putExtra("productID", newsList.get(position).getInfoId());
				} else if (newsList.get(position).getType().equals("3")) {
					intent = new Intent(context, SupplyInfoActivity.class);
					intent.putExtra("productid", newsList.get(position).getInfoId());
				} else if (newsList.get(position).getType().equals("4")) {
					intent = new Intent(context, BuyInfoActivity.class);
					intent.putExtra("productid", newsList.get(position).getInfoId());
				} else if (newsList.get(position).getType().equals("5")) {
					intent = new Intent(context, CompanyInfoActivity.class);
					intent.putExtra("companyID", newsList.get(position).getInfoId());
				}
				context.startActivity(intent);
			}
		});
		news_listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				// TODO 拖动刷新
				page++;
				favsListTask();
			}
		});
		favsListTask();
	}

	private void init() {
		page = 1;
	}

	private void initview() {

	}

	private static class ViewHolder {
		public ImageView img;
		public TextView content;
		public Button button;
	}

	private class NewsListAdapter extends BaseAdapter {

		private List<FavInfo> topics;
		private LayoutInflater mlinflater;

		public NewsListAdapter(Context context, List<FavInfo> list) {
			this.mlinflater = LayoutInflater.from(context);
			this.topics = list;
		}

		@Override
		public int getCount() {
			return topics.size();
		}

		@Override
		public Object getItem(int position) {
			return Integer.valueOf(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup viewGroup) {
			final FavInfo topic = topics.get(position);
			if (view == null) {
				view = mlinflater.inflate(R.layout.fav_list_item, null);
				ViewHolder vh = new ViewHolder();
				vh.content = (TextView) view.findViewById(R.id.list_fav_content);
				vh.img = (ImageView) view.findViewById(R.id.list_fav_img);
				vh.button = (Button) view.findViewById(R.id.list_fav_button);
				view.setTag(vh);
			}
			ViewHolder holder = (ViewHolder) view.getTag();

			if (topic.getType().equals("1")) {
				holder.img.setImageResource(R.drawable.icon_news);
			} else if (topic.getType().equals("2")) {
				holder.img.setImageResource(R.drawable.icon_goods);
			} else if (topic.getType().equals("3")) {
				holder.img.setImageResource(R.drawable.icon_supply);
			} else if (topic.getType().equals("4")) {
				holder.img.setImageResource(R.drawable.icon_want);
			} else if (topic.getType().equals("5")) {
				holder.img.setImageResource(R.drawable.icon_company);
			}
			holder.content.setText(Html.fromHtml(topic.getType() + ":" + topic.getInfoName()));

			holder.button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 删除收藏
					FavoriteList.this.deleteFavTask(topic.getId(), position);
				}
			});
			// holder.button.setVisibility(View.GONE);
			return view;
		}
	}

	private void favsListTask() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "favouritesList");
		map.put("userId", app.user.getId());
		map.put("type", "" + type);
		map.put("currentPage", "" + page);
		map.put("rowCountPerPage", "10");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}

			private void parseJson(JSONObject response) {
				try {
					String currentPage = response.getString("currentPage");
					String totalPage = response.getString("totalPage");
					if (Constant.debug)
						Log.d("stop", currentPage);
					if (Constant.debug)
						Log.d("stop", totalPage);
					if (currentPage.equals(totalPage)) {
						news_listView.loadComplete(false);
					}

					JSONArray list = new JSONArray(response.getString("dataList"));
					for (int i = 0; i < list.length(); i++) {
						FavInfo one = new FavInfo();
						JSONObject favs = list.getJSONObject(i);
						one.setId(favs.getString("id"));
						one.setInfoId(favs.getString("infoId"));
						one.setInfoName(favs.getString("infoName"));
						one.setType(favs.getString("type"));
						one.setCreatetime(favs.getString("createtime"));
						newsList.add(one);
					}
					newsListAdapter.notifyDataSetChanged();
					news_view.show();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

	}

	private void deleteFavTask(String id, final int removeid) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "infoDelete");
		map.put("userId", app.user.getId());
		map.put("id", id);
		map.put("type", "5");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}

			private void parseJson(JSONObject response) {
				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {
						newsList.remove(removeid);
						Toast toast = Toast.makeText(content, "删除成功。", Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					} else {
						Toast toast = Toast.makeText(content, "删除失败。", Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
					newsListAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

	}

}
